package com.topisv.tms.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.ShopSource;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.jms.vo.SendOutMessage;
import com.topisv.tms.service.edb.EdbTaskService;
import com.topisv.tms.service.vo.invoice.MDParam;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.utils.SystemUtil;
import com.topisv.tms.utils.TimeUtil;
import com.topisv.tms.utils.TopUtils;

import net.sf.json.JSONObject;

@Component
public class SendOutOrdenoHT {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private EdiOrderService ediOrderService;
	@Autowired
	private EdiOrderItemService ediOrderItemService;
	@Autowired
	private ShopSourceService shopSourceService;
	@Autowired
	private WorkOrderService workOrderService;
	
	@Autowired
	private EdbTaskService edbTaskService;
	
	public List<SendOutMessage> getSendOutMessage(String ordeno)throws Exception{
		List<SendOutMessage> sendOutMessages=new ArrayList<SendOutMessage>();
		
		EdiOrder e=ediOrderService.findByOrdeno(ordeno);
		if("cancel".equals(e.getOrderStatus())){
			return null;
		}
		if(ordeno.endsWith("R"))
		{
			return null;
		}
		ShopSource shopSource=shopSourceService.findByShopCode(e.getShopCode());
		if(null == shopSource || null == shopSource.getHtSendUrl())
		{
			return null;
		}
		if("LMB".equals(e.getCustomerCode()))
		{
			WorkOrder workOrder=workOrderService.loadOrder(e.getBatchTaskCode(), ordeno);
			JSONObject json = new JSONObject();
			String logisticCode = "";
			if("ebill".equals(workOrder.getBillType())){
				logisticCode =workOrder.getEbillNo();
			}else{
				logisticCode =workOrder.getExpressNo();
			}
			json.put("orderCode", e.getFromno());
			json.put("logisticCode", workOrder.getExpressCompany());
			json.put("expressCode", logisticCode);
			String data=json.toString();
			String url = MDParam.LMB_URL_POSTEXPRESSNO;
			String appkey=MDParam.LMB_APPKEY;
			String md5 = SystemUtil.MD5(appkey + data + MDParam.LMB_KEYWORD);
			String appsecret = SystemUtil.getBASE64(md5);
			
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("appkey", appkey));
			nvps.add(new BasicNameValuePair("appsecret", appsecret));
			nvps.add(new BasicNameValuePair("data", data));
			logger.info("辣妈帮发货：" + "appkey="+appkey + "&appsecret="+ appsecret +"&data=" + data );
			HttpClient httpClient = new DefaultHttpClient();
			org.apache.http.client.methods.HttpPost httpPost = new org.apache.http.client.methods.HttpPost(url);
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
			HttpResponse response;
			try {
				response = httpClient.execute(httpPost);
				if (response.getStatusLine().getStatusCode() == 200){
					String result=EntityUtils.toString(response.getEntity());
					logger.info("辣妈帮发货结果：" + result);
					JSONObject resJson = JSONObject.fromObject(result);
					if(!"0".equals(resJson.getString("code")))
					{
						workOrder.setSendOutStatus("fail");
					}
					else
					{
						workOrder.setSendOutStatus("finish");
					}
				} else {
					workOrder.setSendOutStatus("fail");
					EntityUtils.consume(response.getEntity());
					//throw new RuntimeException("response status error: " + response.getStatusLine().getStatusCode());
				}
				workOrderService.save(workOrder);
			} catch (ClientProtocolException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			} catch (Exception e3) {
				// TODO Auto-generated catch block
				e3.printStackTrace();
			}
		}
		/*
		if("edb".equals(e.getErpType()))
		{
			WorkOrder workOrder=workOrderService.loadOrder(e.getBatchTaskCode(), ordeno);
			StringBuffer buffer = new StringBuffer();
			String logisticCode = "";
			if("ebill".equals(workOrder.getBillType())){
				logisticCode =workOrder.getEbillNo();
			}else{
				logisticCode =workOrder.getExpressNo();
			}
			String expressCode = workOrder.getExpressCompany();
			String expressName = "";
			if("YTO".equals(expressCode))
			{
				expressName = "圆通速递";
			}
			else if("SF".equals(expressCode))
			{
				expressName = "顺丰速运";
			}
			else if("STO".equals(expressCode))
			{
				expressName = "申通快递";
			}
			else if("ZTO".equals(expressCode))
			{
				expressName = "中通快递";
			}
			else if("POSTB".equals(expressCode))
			{
				expressName = "包裹/平邮";
			}
			else if("QRT".equals(expressCode))
			{
				expressName = "增益速递";
			}
			else if("EMS".equals(expressCode))
			{
				expressName = "EMS";
			}
			else if("YUNDA".equals(expressCode))
			{
				expressName = "韵达";
			}
			else if("DBL".equals(expressCode))
			{
				expressName = "德邦物流";
			}
			else
			{
				expressName = expressCode;
			}
			String timestamp = TimeUtil.getNowDateString();
			buffer.append("<order>").append("<orderInfo>");
			buffer.append("<tid>").append(e.getFromno()).append("</tid>");
			buffer.append("<out_tid>").append("").append("</out_tid>");
			buffer.append("<express>").append(expressName).append("</express>");
			buffer.append("<delivery_time>").append(timestamp).append("</delivery_time>");
			buffer.append("<express_code>").append(expressCode).append("</express_code>");
			buffer.append("<express_no>").append(logisticCode).append("</express_no>");
			buffer.append("<printer>").append("打单员").append("</printer>");
			buffer.append("<Cargo_operator>").append("配货员").append("</Cargo_operator>");
			buffer.append("<Cargo_time>").append(timestamp).append("</Cargo_time>");
			buffer.append("<print_time>").append(timestamp).append("</print_time>");
			buffer.append("<inspecter>").append("验货员").append("</inspecter>");
			buffer.append("<inspect_time>").append(timestamp).append("</inspect_time>");
			buffer.append("<is_inspect_delivery>").append("0</is_inspect_delivery>");
			buffer.append("<delivery_operator>").append("发货员").append("</delivery_operator>");
			buffer.append("<GrossWeight>").append("</GrossWeight>");
			buffer.append("<internal_note>").append("</internal_note>");
			buffer.append("<origin_code>").append("</origin_code>");
			buffer.append("<dest_code>").append("</dest_code>");
			buffer.append("</orderInfo>").append("<productInfo>");
			buffer.append("<product_item>").append("<tid></tid><barCode></barCode><inspection_num></inspection_num>").append("</product_item>");
			buffer.append("</productInfo>").append("</order>");
			EdbTask edbTask = edbTaskService.findTask(workOrder.getCustomerCode(),workOrder.getWarehouseCode(),"edbTradeUpdate");
			String params =EdbAPITool.edbParamGet(buffer.toString(), edbTask);
			SendOutMessage sendOutMessage=new SendOutMessage();
			sendOutMessage.setUrl(shopSource.getHtSendUrl());
			sendOutMessage.setParams(params);
			sendOutMessage.setOrdeno(ordeno);
			sendOutMessages.add(sendOutMessage);
			return sendOutMessages;
			
		}
		 */
		if("MLS".equals(e.getCustomerCode()))
		{
			WorkOrder workOrder=workOrderService.loadOrder(e.getBatchTaskCode(), ordeno);
			JSONObject json = null;
			try {
				json = new JSONObject();
				json.put("orderCode", e.getFromno());
				json.put("customerCode", e.getPlatformCustomerCode());
				String expressCode = workOrder.getExpressCompany();
				String expressName = "";
				if("YTO".equals(expressCode))
				{
					expressName = "圆通速递";
				}
				else if("SF".equals(expressCode))
				{
					expressName = "顺丰速运";
				}
				else if("STO".equals(expressCode))
				{
					expressName = "申通快递";
				}
				else if("ZTO".equals(expressCode))
				{
					expressName = "中通快递";
				}
				else if("POSTB".equals(expressCode))
				{
					expressName = "包裹/平邮";
				}
				else if("QRT".equals(expressCode))
				{
					expressName = "增益速递";
				}
				else if("EMS".equals(expressCode))
				{
					expressName = "EMS";
				}
				else if("YUNDA".equals(expressCode))
				{
					expressName = "韵达";
				}
				else
				{
					expressName = expressCode;
				}
				json.put("logisticCode", expressName);
				if("ebill".equals(workOrder.getBillType())){
					json.put("expressCode", workOrder.getEbillNo());
				}else{
					json.put("expressCode", workOrder.getExpressNo());
				}
				List<EdiOrderItem> items = ediOrderItemService.findByOrdeno(ordeno);
				String mids = "";
				for(EdiOrderItem item : items)
				{
					if(!"".equals(mids))
					{
						mids += "_" + item.getMidId();
					}
					else
					{
						mids = item.getMidId();
					}
				}
				json.put("mids", mids);
			    String appkey = shopSource.getHtKey();
			    String appsecret = shopSource.getHtSecret();
			    String secret = SystemUtil.getBASE64(SystemUtil.MD5(appkey +json.toString()+  appsecret));
			    String url = shopSource.getHtSendUrl();
			    SendOutMessage sendOutMessage=new SendOutMessage();
			    sendOutMessage.setUrl(url);
				sendOutMessage.setParams("appkey=" + appkey + "&appsecret=" + secret + "&data=" + json.toString());
				sendOutMessage.setOrdeno(ordeno);
				sendOutMessages.add(sendOutMessage);
				return sendOutMessages;
			} catch (Exception e1) {
				throw e1;
			}
		}
		if("HHQZ".equals(e.getCustomerCode()))
		{
			WorkOrder workOrder=workOrderService.loadOrder(e.getBatchTaskCode(), ordeno);
			try {
				String fromno = e.getFromno();
				String[] orderCodes = fromno.split(":");
				for(String orderCode : orderCodes)
				{
					String expressCode = workOrder.getExpressCompany();
					if("YTO".equals(expressCode))
					{
						expressCode = "yuantong";
					}
					else if("SF".equals(expressCode))
					{
						expressCode = "shunfeng";
					}
					else if("STO".equals(expressCode))
					{
						expressCode = "shentong";
					}
					else if("ZTO".equals(expressCode))
					{
						expressCode = "zhongtong";
					}
					else if("POSTB".equals(expressCode))
					{
						expressCode = "youzhengguonei";
					}
					else if("QRT".equals(expressCode))
					{
						expressCode = "zengyi";
					}
					else
					{
						expressCode = "";
					}
					String logisticCode = "";
					if("ebill".equals(workOrder.getBillType())){
						logisticCode =workOrder.getEbillNo();
					}else{
						logisticCode =workOrder.getExpressNo();
					}
					
				    String appkey = shopSource.getHtKey();
				    String appsecret = shopSource.getHtSecret();
				    String url = shopSource.getHtSendUrl();
				    SendOutMessage sendOutMessage=new SendOutMessage();
				    sendOutMessage.setUrl(url);
					sendOutMessage.setParams("appkey=" + appkey + "&appsecret=" + appsecret + "&orderCode=" 
							+ orderCode + "&expressCode=" + expressCode + "&logisticCode=" + logisticCode);
					sendOutMessage.setOrdeno(ordeno);
					sendOutMessages.add(sendOutMessage);
				}
				
				return sendOutMessages;
			} catch (Exception e1) {
				throw e1;
			}
		}
		if("oms".equals(e.getErpType()))
		{
			WorkOrder workOrder=workOrderService.loadOrder(e.getBatchTaskCode(), ordeno);
			JSONObject json = null;
			try {
				json = new JSONObject();
				json.put("ordeno", ordeno);
				String expressCode = workOrder.getExpressCompany();
				
				String logisticCode = "";
				if("ebill".equals(workOrder.getBillType())){
					logisticCode =workOrder.getEbillNo();
				}else{
					logisticCode =workOrder.getExpressNo();
				}
				json.put("mailNo", logisticCode);
				json.put("companyCode", expressCode);
			    String appkey = shopSource.getHtKey();
			    String appsecret = shopSource.getHtSecret();
			    String url = shopSource.getHtSendUrl();
			    SendOutMessage sendOutMessage=new SendOutMessage();
			    sendOutMessage.setUrl(url);
				sendOutMessage.setParams("appkey=" + appkey + "&appsecret=" + appsecret + "&json=" 
						+ json.toString());
				sendOutMessage.setOrdeno(ordeno);
				sendOutMessages.add(sendOutMessage);
				return sendOutMessages;
			} catch (Exception e1) {
				throw e1;
			}
		}
		if("fr".equals(e.getErpType()))
		{
			
	        try {
	        	WorkOrder workOrder=workOrderService.loadOrder(e.getBatchTaskCode(), ordeno);
	        	String expressCode = workOrder.getExpressCompany();
	        	String tmsName = "";
				JSONObject json = new JSONObject();;
				json.put("BIL_NO", e.getCustomerOrdeno());
				json.put("TmsCode", expressCode);
				if("STO".equals(expressCode))
				{
					tmsName = "申通快递";
				}
				else if("SF".equals(expressCode))
				{
					tmsName = "顺丰速运";
				}
				else if("YTO".equals(expressCode))
				{
					tmsName = "圆通速递";
				}
				else if("POSTB".equals(expressCode))
				{
					tmsName = "邮政小包";
				}
				else if("QRT".equals(expressCode))
				{
					tmsName = "增益速递";
				}
				else if("EMS".equals(expressCode))
				{
					tmsName = "EMS";
				}
				else if("YUNDA".equals(expressCode))
				{
					tmsName = "韵达";
				}
				else if("UC".equals(expressCode))
				{
					tmsName = "优速";
				}
				else
				{
					tmsName = expressCode;
				}
				json.put("TmsName", tmsName);
				if("ebill".equals(workOrder.getBillType())){
					json.put("TransportNo", workOrder.getEbillNo());
				}else{
					json.put("TransportNo", workOrder.getExpressNo());
				}
				json.put("OrderStatus", "FINISHED");
				json.put("FailReason", "");
				Map<String,String> map = new HashMap<String,String>();
				String session = "";
				String Content = "[" + json.toString() + "]";
				String WMSSIGN = shopSource.getHtSecret();
				String Service = "orderStatus";
				String timestamp = TimeUtil.getNowDateString();
				String method = "paiu.trades.update";
				map.put("WMSID", shopSource.getHtKey());
				map.put("Content", Content);
				map.put("method", method);
				map.put("Service", Service);
				map.put("timestamp", TimeUtil.getNowDateString());
				session = TopUtils.signTopRequestNew(map,WMSSIGN,false);
				
				String params = "Content=" + Content + "&method=" + method + "&Service=" + Service + "&session=" + session 
	     		   + "&timestamp=" + timestamp + "&WMSID=" + shopSource.getHtKey();
				SendOutMessage sendOutMessage=new SendOutMessage();
				sendOutMessage.setUrl(shopSource.getHtSendUrl());
				sendOutMessage.setParams(params);
				sendOutMessage.setOrdeno(ordeno);
				sendOutMessages.add(sendOutMessage);
				return sendOutMessages;
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				
			}
		}
		if(shopSource==null||(!"ht".equals(shopSource.getOrdenoSourceCode()))){
			return null;
		}
		WorkOrder workOrder=workOrderService.loadOrder(e.getBatchTaskCode(), ordeno);
		try {
			String customersOrdeno=e.getCustomerOrdeno();
			String[] ordenos=customersOrdeno.split(":");
			for(String o:ordenos){
				if(!"".equals(o)){
					SendOutMessage sendOutMessage=new SendOutMessage();
					StringBuffer sb=new StringBuffer();
					sb.append("orderCode="+o);
					if("ebill".equals(workOrder.getBillType())){
						sb.append("&expressCode="+workOrder.getEbillNo());
					}else{
						sb.append("&expressCode="+workOrder.getExpressNo());
					}
					sb.append("&appkey="+shopSource.getHtStockUser());
					sb.append("&appsecret="+shopSource.getHtStockSign());
					sb.append("&logisticCode="+workOrder.getExpressCompany());
					sb.append("&force=0");
					sendOutMessage.setUrl(shopSource.getHtSendUrl());
					sendOutMessage.setParams(sb.toString());
					sendOutMessage.setOrdeno(ordeno);
					sendOutMessages.add(sendOutMessage);
				}
			}
			return sendOutMessages;
		} catch (Exception e1) {
			throw e1;
		}
	}
}
